export class WebSocketClient {
  private socket: WebSocket;

  constructor(senid:string) {
    this.socket = new WebSocket('ws:192.168.128.40:8080/api/customer/'+senid);
    this.setupListeners();
  }

  private setupListeners() {
    this.socket.onopen = () => {
      console.log('WebSocket connection opened');
    };

    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.onMessage(data);
    };

    this.socket.onclose = () => {
      console.log('WebSocket connection closed');
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
  }

  on(event: string, callback: (data: any) => void) {
    if (event === 'message') {
      this.onMessage = callback;
    }
  }

  send(data: any) {
    this.socket.send(JSON.stringify(data));
  }

  connect(senid) {
    if (this.socket.readyState === WebSocket.CLOSED || this.socket.readyState === WebSocket.CLOSING) {
      this.socket = new WebSocket('ws:192.168.128.40:8080/api/customer/'+senid);
      this.setupListeners();
    }
  }

  private onMessage: (data: any) => void = (data) => {};
}
